const { Router } = require('express')
const path = require('path')
const sqlite3 = require('sqlite3').verbose()
const {promise: getBody} = require('../utils/req-post-body.js')

const users = new sqlite3.Database(path.join(__dirname, '../databases/users.db'))
let reqGetCodeCounts = 0
/**
 * @type {Array<[import('express').Request, import('express').Response]>}
 */
let reqGetCodeReqAndRes = []

function getNewCode() {
    if (reqGetCodeCounts == 0)
        return
    let code = ''
    for (let i = 0; i < 10; i++) {
        let thisC = Math.floor(Math.random() * 36).toString(36)
        if (Math.floor(Math.random() * 2) === 0) thisC = thisC.toUpperCase()
        code += thisC
    }
    users.run(`INSERT INTO code (code) VALUES ('${code}')`, function (err) {
        if (err) {
            console.log(err)
            reqGetCodeReqAndRes[reqGetCodeCounts - 1][1].json({ success: false })
            reqGetCodeReqAndRes.pop()
            reqGetCodeCounts--
            return
        }
        const [req, res] = reqGetCodeReqAndRes[reqGetCodeCounts - 1]
        res.cookie('htqw-blog-2-code-id', this.lastID, {maxAge: 60, httpOnly: true, sameSite: 'strict', path: '/'})
        res.json({
            success: true
        })
        reqGetCodeReqAndRes.pop()
        reqGetCodeCounts--
        if (reqGetCodeCounts > 0)
            getNewCode()
    })
}

const router = Router()
router.post('/setup', async (req, res) => {
    const body = await getBody(req)
    console.log(body)
    res.send(body)
})
router.post('/setup/code', async (req, res) => {
    reqGetCodeCounts++
    reqGetCodeReqAndRes.push([req, res])
    if (reqGetCodeCounts == 1) {
        getNewCode()
    }
})

module.exports = router